package pos;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;

import net.ck.hzq.R;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.compress.CompressConfig;
import org.devio.takephoto.model.CropOptions;
import org.devio.takephoto.model.TImage;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.model.TakePhotoOptions;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

import Bean.PhoneNumerBean;
import Bean.PhoneNumerParamBean;
import Utils.FileUtil;
import Utils.HelloWordModel;
import Utils.OCRUtils;
import Utils.SharedPrefStore;
import Utils.SystemDatas;
import Utils.ToastUtil;
import activity.VerifyingActivity;
import activity.glide.GlideApp;
import base.BaseActivity;
import base.BaseTakePhotoActivity;
import dao.AddPosInput;
import dao.BaseOutput;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ui.activity.profit.biz.ProfitBiz;
import util.LogUtils;
import util.PermissionUtils;
import widget.CitySelectView;

import static Utils.FileUtil.compress;

/**
 * by BF00233 on 2018/12/15.
 */
public class OldPosAuthByHandActivity extends BaseTakePhotoActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_PICK_IMAGE_FRONT = 201;
    private static final int REQUEST_CODE_PICK_IMAGE_BACK = 202;
    private static final int REQUEST_CODE_FACE = 203;
    private static final int REQUEST_CODE_CAMERA = 102;
    private static final int REQUEST_CODE_BANKCARD = 111;
    private static final int REQUEST_CODE_BANKCARDBACK = 112;
    private static final int REQUEST_CODE_BUSINESS_LICENSE = 113;
    private static final int REQUEST_CODE_DOOR = 114;
    private static final int REQUEST_CODE_ENVIRONMENT = 115;
    ProfitBiz profitBiz;
    private CountDownTimer timer;
    private String mCode;
    private int clickType = -1;

    // 1-扫描身份证正面 2-身份证反面 3-确认身份证信息　4-手持认证 ５-银行卡正面，6-银行卡背面 7-填写所有信息
    private int mStep = 1;

    // 身份证信息
    private String mIdAddress, mIdName, mIdNo, mIdGender, mIdDate;
    // 银行卡信息
    private String cardNum, cardType, cardBank, cardVerificationCode;
    // 照片缓存路径
    private String mImagePathIdFront, mImagePathIdBack, mImagePathHand,
            mImagePathBankCard, mImagePathBusinessLicense;
    // 照片 base64 数据
    private String base64_id_front, base64_id_back, base64_hand, base64_back_card,base64_back_card_back,
             base64_business_license, base64_door,base64_environment;

    private ScrollView scrollView;
    private TextView warnTip,posauthbyhandsubmitbutton,tv_rate;
    private ViewGroup imageLayout;
    private ImageView authImage;
    private RelativeLayout rate_layout;
    private LinearLayout doorlayout;//门头照的linear


    // 详细信息填写
    private ViewGroup detailInfoLayout;
    private ImageView idFrontIv, idBackIv, holdIv, bankCardIv,hand_image_bank_card_back, businessLicenseIv,hand_image_id_door,hand_image_id_enerment;
    private EditText detailIdNo, detailIdName;
    private AppCompatEditText bankCardNameEt, bankCardNoEt, phoneEt, verifyCodeEt, snEt,
            openAccountBankEt, detailAddressEt,et_email;

    private TextView merchantTypeTv;
    // 验证码
    private TextView getVerifyCode;

    private CitySelectView citySelectView;
    private String mAddressCode;
    private TextView addressSelectTv,auto_scan_sn;
    private ImageView sm_back;
    private String mMerchantType;
    private String ratenum;//费率

    //申请权限
    private final String[] PERMISSIONS = new String[]{Manifest.permission.CAMERA,
          Manifest.permission.WRITE_EXTERNAL_STORAGE,

    };
    private final int REQUEST_WRITE = 2;
    public static void start(Context context) {
        Intent intent = new Intent(context, OldPosAuthByHandActivity.class);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_old_pos_authbyhand;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        profitBiz = new ProfitBiz();
        sm_back = findViewById(R.id.sm_back);
        detailIdNo = findViewById(R.id.detail_id_no);
        detailIdName = findViewById(R.id.detail_id_name);
        auto_scan_sn = findViewById(R.id.auto_scan_sn);
        tv_rate = findViewById(R.id.tv_rate);
        doorlayout = findViewById(R.id.doorlayout);
        posauthbyhandsubmitbutton = findViewById(R.id.posauthbyhandsubmitbutton);
//
        bankCardNameEt = findViewById(R.id.et_bank_card_name);
        bankCardNoEt = findViewById(R.id.et_bank_card_no);
        phoneEt = findViewById(R.id.et_merchant_phone);
        verifyCodeEt = findViewById(R.id.et_verify_code);
        snEt = findViewById(R.id.et_sn);
        addressSelectTv = findViewById(R.id.address_input);
        merchantTypeTv = findViewById(R.id.merchant_type);
        openAccountBankEt = findViewById(R.id.et_open_account_bank);
        detailAddressEt = findViewById(R.id.et_address);
        et_email = findViewById(R.id.et_email);
        rate_layout = findViewById(R.id.rate_layout);
//
        idFrontIv = findViewById(R.id.hand_image_id_card_front);
        idBackIv = findViewById(R.id.hand_image_id_card_back);
        hand_image_id_door  = findViewById(R.id.hand_image_id_door);
        hand_image_id_enerment = findViewById(R.id.hand_image_id_enerment);
        holdIv = findViewById(R.id.hand_image_hold);
        bankCardIv = findViewById(R.id.hand_image_bank_card);
        hand_image_bank_card_back= findViewById(R.id.hand_image_bank_card_back);
        businessLicenseIv = findViewById(R.id.hand_image_business_license);
//
//        extraImageLayout = findViewById(R.id.extra_image_layout);
//        doorIv = findViewById(R.id.image_door);
//        environmentIv = findViewById(R.id.image_environment);
//
        // 验证码
        getVerifyCode = findViewById(R.id.get_verify_code);
        getVerifyCode.setOnClickListener(this);
        idFrontIv.setOnClickListener(this);
        auto_scan_sn.setOnClickListener(this);
        posauthbyhandsubmitbutton.setOnClickListener(this);
        idBackIv.setOnClickListener(this);
        holdIv.setOnClickListener(this);
        bankCardIv.setOnClickListener(this);
        businessLicenseIv.setOnClickListener(this);
        hand_image_bank_card_back.setOnClickListener(this);
        tv_rate.setOnClickListener(this);
        sm_back.setOnClickListener(this);
        rate_layout.setOnClickListener(this);
        hand_image_id_door.setOnClickListener(this);
        hand_image_id_enerment.setOnClickListener(this);

//
//        // 商户类型选择
        findViewById(R.id.merchant_type_layout).setOnClickListener(this);
//
//        // 地址选择
        findViewById(R.id.address_layout).setOnClickListener(this);
        citySelectView = findViewById(R.id.city_select_view);
        citySelectView.setAddressSelectedListener((code, address) -> {
            mAddressCode = code;
            citySelectView.setVisibility(View.GONE);
            addressSelectTv.setText(address);
            addressSelectTv.setTextColor(getResources().getColor(R.color.tc_666666));
            LogUtils.d("+++++11111省市地址数据+++++++++++"+address);
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.hand_image_business_license:
//                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//                    OCRUtils.startBusinessLicense2(this, REQUEST_CODE_BUSINESS_LICENSE);
//                } else {
//                    requestMorePermissions(1);
//                }
                clickType = 6;
                cameraClick2(clickType,getTakePhoto());
                break;
            case R.id.hand_image_id_card_front:

//                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//                    OCRUtils.startIDCardFront(this, REQUEST_CODE_PICK_IMAGE_FRONT);
//                } else {
//                    requestMorePermissions(2);
//                }

                clickType = 1;
                cameraClick(clickType,getTakePhoto());
                break;
            case R.id.hand_image_id_card_back:

//                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//                    OCRUtils.startIDCardBack(this, REQUEST_CODE_PICK_IMAGE_BACK);
//                } else {
//                    requestMorePermissions(3);
//                }
                clickType = 2;
                cameraClick(clickType,getTakePhoto());
                break;
            case R.id.hand_image_hold:
//
//                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//                    OCRUtils.startFace2(this, REQUEST_CODE_FACE);
//                } else {
//                    requestMorePermissions(4);
//                }
                clickType = 3;
                cameraClick(clickType,getTakePhoto());
                break;
            case R.id.hand_image_bank_card:

//                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//                    OCRUtils.startBankCard(this, REQUEST_CODE_BANKCARD);
//                } else {
//                    requestMorePermissions(5);
//                }
                clickType = 4;
                cameraClick(clickType,getTakePhoto());
                break;
            case R.id.hand_image_bank_card_back:

//                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//                    OCRUtils.startBankCardBack2(this, REQUEST_CODE_BANKCARDBACK);
//                } else {
//                    requestMorePermissions(6);
//                }
                clickType = 5;
                cameraClick(clickType,getTakePhoto());
                break;
            case R.id.address_layout:
                citySelectView.setVisibility(View.VISIBLE);
                break;
            case R.id.hand_image_id_door:

//                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//                    OCRUtils.startDoor(this, REQUEST_CODE_DOOR);
//                } else {
//                    requestMorePermissions(7);
//                }
                clickType = 7;
                cameraClick2(clickType,getTakePhoto());
                break;
            case R.id.hand_image_id_enerment:

//                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//                    OCRUtils.startEnvironment(this, REQUEST_CODE_ENVIRONMENT);
//                } else {
//                    requestMorePermissions(8);
//                }
                clickType = 8;
                cameraClick2(clickType,getTakePhoto());
                break;
            case R.id.merchant_type_layout:
                showSelectBankTypeDialog();
                break;
            case R.id.auto_scan_sn:
                IntentIntegrator integrator = new IntentIntegrator(OldPosAuthByHandActivity.this);
                // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
                integrator.setCaptureActivity(ScanActivity.class); //设置打开摄像头的Activity
                integrator.setPrompt("请扫描SN"); //底部的提示文字，设为""可以置空
                integrator.setCameraId(0); //前置或者后置摄像头
                integrator.setBeepEnabled(true); //扫描成功的「哔哔」声，默认开启
                integrator.setBarcodeImageEnabled(true);
                integrator.initiateScan();
                break;


            case R.id.rate_layout:
//                profitBiz.GetUserRate2(new BaseBiz.Callback<List<String>>() {
//                    @Override
//                    public void onSuccess(List<String> info) {
//                        String[] items = new String[info.size()];
//                        for (int i = 0;i<info.size();i++){
//                            items[i]=info.get(i);
//                        }
//                        new QMUIDialog.CheckableDialogBuilder(OldPosAuthByHandActivity.this)
//                                .addItems(items, (dialogInterface, i) -> {
//                                    ratenum = items[i];
//                                    tv_rate.setText(ratenum);
//                                    tv_rate.setTextColor(getResources().getColor(R.color.tc_666666));
//                                    dialogInterface.dismiss();
//                                })
//                                .create()
//                                .show();
//
//                    }
//
//                    @Override
//                    public void onFailure(List<String> info) {
//
//                    }
//                });
//                SharedPrefStore store = new SharedPrefStore();
//              String   customId = store.getString("id", "0");
//                profitBiz.GetUserRate(customId ,new BaseBiz.Callback<RateLevelBean>() {
//                    @Override
//                    public void onSuccess(RateLevelBean info) {
//
//                        if(info.getLevelAmount()<=5){
//                            showLevelRate();
//                        }else{
//                            showLevelRate2();
//                        }
//
//                    }
//
//                    @Override
//                    public void onFailure(RateLevelBean info) {
//
//                    }
//                });
                break;
            case R.id.get_verify_code:
                requestVerifyCode();
                break;
            case R.id.sm_back:
                finish();
                break;
            case R.id.posauthbyhandsubmitbutton:
                submitData();
                break;
        }
    }

    //拍照
    private void cameraClick(int type, TakePhoto takePhoto) {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri imageUri = Uri.fromFile(file);
        configCompress(takePhoto);
        configTakePhotoOption(takePhoto);
        takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
    }
    //拍照
    private void cameraClick2(int type, TakePhoto takePhoto) {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri imageUri = Uri.fromFile(file);
        configCompress(takePhoto);
        configTakePhotoOption(takePhoto);
        takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions2());
    }
    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true); //使用TakePhoto自带小相册
        builder.setCorrectImage(true); //纠正拍照的照片旋转角度
        takePhoto.setTakePhotoOptions(builder.create());
    }

    private CropOptions getCropOptions() {
        int height = 600;
        int width = 800;
        boolean withWonCrop = false;

        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);
        builder.setWithOwnCrop(withWonCrop);
        return builder.create();
    }
    private CropOptions getCropOptions2() {
        int height = 1200;
        int width = 800;
        boolean withWonCrop = false;

        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);
        builder.setWithOwnCrop(withWonCrop);
        return builder.create();
    }

    private void configCompress(TakePhoto takePhoto) {
        int maxSize = 102400;
        int width = 800;
        int height = 800;
        boolean showProgressBar = false;
        boolean enableRawFile = true;
        CompressConfig config;
//        if (rgCompressTool.getCheckedRadioButtonId() == R.id.rbCompressWithOwn) {
        config = new CompressConfig.Builder().setMaxSize(maxSize)
                .setMaxPixel(width >= height ? width : height)
                .enableReserveRaw(enableRawFile)
                .create();
//        } else {
//            LubanOptions option = new LubanOptions.Builder().setMaxHeight(height).setMaxWidth(width).setMaxSize(maxSize).create();
//            config = CompressConfig.ofLuban(option);
//            config.enableReserveRaw(enableRawFile);
//        }
        takePhoto.onEnableCompress(config, showProgressBar);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        showImg(result.getImages());

    }
//    private ImageView idFrontIv, idBackIv, holdIv, bankCardIv,hand_image_bank_card_back, businessLicenseIv,hand_image_id_door,hand_image_id_enerment;
//private String base64_id_front, base64_id_back, base64_hand, base64_back_card,base64_back_card_back,
//        base64_business_license, base64_door,base64_environment;
    private void showImg(ArrayList<TImage> images) {
        if (clickType == 1){

            base64_id_front = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(idFrontIv);
        }
        else if (clickType == 2){
            base64_id_back = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(idBackIv);
        }
        else if (clickType == 3){
            base64_hand = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(holdIv);
        }
        else if (clickType == 4){
            base64_back_card = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(bankCardIv);
        } else if (clickType == 5){
            base64_back_card_back = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(hand_image_bank_card_back);
        } else if (clickType == 6){
            base64_business_license = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(businessLicenseIv);
        } else if (clickType == 7){
            base64_door = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(hand_image_id_door);
        } else if (clickType == 8){
            base64_environment = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(hand_image_id_enerment);
        }
    }


    private void showSelectBankTypeDialog() {
        String[] items = new String[]{"餐娱类", "民生类", "一般类", "公益类", "房产汽车类"};
        new QMUIDialog.CheckableDialogBuilder(this)
//                .setCheckedIndex(Arrays.binarySearch(items, mMerchantType))
                .addItems(items, (dialogInterface, i) -> {
                    mMerchantType = items[i];
                    merchantTypeTv.setText(mMerchantType);
                    merchantTypeTv.setTextColor(getResources().getColor(R.color.tc_666666));
                    dialogInterface.dismiss();
                })
                .create()
                .show();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=timer){
            timer.cancel();
        }
    }
    //level<=3
    private void showLevelRate() {
        String[] items = new String[]{"0.60%","0.61%","0.62%","0.63%","0.64%","0.65%"};
        new QMUIDialog.CheckableDialogBuilder(this)
//                .setCheckedIndex(Arrays.binarySearch(items, mMerchantType))
                .addItems(items, (dialogInterface, i) -> {
                    ratenum = items[i];
                    tv_rate.setText(ratenum);
                    tv_rate.setTextColor(getResources().getColor(R.color.tc_666666));
                    dialogInterface.dismiss();
                })
                .create()
                .show();
    }
    //level>=4
    private void showLevelRate2() {
        String[] items = new String[]{"0.55%","0.56%","0.57%","0.58%","0.59%","0.60%","0.61%","0.62%","0.63%","0.64%","0.65%"};
        new QMUIDialog.CheckableDialogBuilder(this)
//                .setCheckedIndex(Arrays.binarySearch(items, mMerchantType))
                .addItems(items, (dialogInterface, i) -> {
                    ratenum = items[i];
                    tv_rate.setText(ratenum);
                    tv_rate.setTextColor(getResources().getColor(R.color.tc_666666));
                    dialogInterface.dismiss();
                })
                .create()
                .show();
    }

    private void submitData() {
        if (!checkDetailInput()) {
            showFailureTipDialog("请输入所有必要信息");
            return;
        }
        showProgressDialog();

        SharedPrefStore store = new SharedPrefStore();
        AddPosInput param = new AddPosInput();
        param.customId = store.getString("id", "0");
        param.merchantName = detailIdName.getText().toString();
        param.idCard = detailIdNo.getText().toString();
        param.phone = phoneEt.getEditableText().toString();
        param.bankCardNumber = bankCardNoEt.getEditableText().toString();
        param.bank = bankCardNameEt.getEditableText().toString();
        param.sn = snEt.getEditableText().toString().trim().replace("\n","");
        param.region = mAddressCode;
        param.rate = tv_rate.getText().toString().replace("%","");
        param.address = detailAddressEt.getEditableText().toString();
        param.qqemail = et_email.getEditableText().toString();
        param.idCardFront = base64_id_front;
        param.idCardBack = base64_id_back;
        param.holdIdCardFront = base64_hand;
        param.bankFont = base64_back_card;
        param.bankBack = base64_back_card_back;
        if (!TextUtils.isEmpty(base64_business_license)) {
            param.businessLicense = base64_business_license;
            param.door = base64_door;
            param.businessment = base64_environment;
        }
        param.khzh = openAccountBankEt.getEditableText().toString();
        param.businessType = mMerchantType;

        Call<BaseOutput<Object>> userMsgCall = HelloWordModel.getInstance(OldPosAuthByHandActivity.this)
                .addTraditionalPos(param);
        userMsgCall.enqueue(new Callback<BaseOutput<Object>>() {
            @Override
            public void onResponse(@NonNull Call<BaseOutput<Object>> call, @NonNull Response<BaseOutput<Object>> response) {
                dismissProgressDialog();
                try{
                if (response.body() != null) {
                    if ("success".equals(response.body().msg)) {
                        VerifyingActivity.start(OldPosAuthByHandActivity.this);
                        finish();
                    } else {
                        showFailureTipDialog(response.body().msg);
                    }
                }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NonNull Call<BaseOutput<Object>> call, @NonNull Throwable t) {
                dismissProgressDialog();
                ToastUtil.show(OldPosAuthByHandActivity.this, "提交失败，请稍后重试");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 身份证正面
        if (requestCode == REQUEST_CODE_PICK_IMAGE_FRONT && resultCode == Activity.RESULT_OK) {
            handleidccardImageSuccess(FileUtil.getSaveFileSfzzm(this).getAbsolutePath(),idFrontIv);
        }else
        // 身份证反面
        if (requestCode == REQUEST_CODE_PICK_IMAGE_BACK && resultCode == Activity.RESULT_OK) {
            handleidccardbackImageSuccess(FileUtil.getSaveFileSfzfm(this).getAbsolutePath(),idBackIv);
        }else
        // 人脸拍摄
        if (requestCode == REQUEST_CODE_FACE && resultCode == Activity.RESULT_OK) {
            handImageSuccess(FileUtil.getSaveFileFace(this).getAbsolutePath(),holdIv);
        }else
        // 银行卡
        if (requestCode == REQUEST_CODE_BANKCARD && resultCode == Activity.RESULT_OK) {
            handlebankccardImageSuccess(FileUtil.getSaveFile(this).getAbsolutePath(),bankCardIv);
        }else
        // 银行卡背面
        if (requestCode == REQUEST_CODE_BANKCARDBACK && resultCode == Activity.RESULT_OK) {
            handlebankcardbackImageSuccess(FileUtil.getBankBackFile(this).getAbsolutePath(),hand_image_bank_card_back);
        }else
        // 营业执照
        if (requestCode == REQUEST_CODE_BUSINESS_LICENSE && resultCode == Activity.RESULT_OK) {
            handlebussissImageSuccess(FileUtil.getBusinessLicense(this).getAbsolutePath(),businessLicenseIv);
            doorlayout.setVisibility(View.VISIBLE);
        }else
        //门头
        if (requestCode == REQUEST_CODE_DOOR && resultCode == Activity.RESULT_OK) {
            handdoorImageSuccess(FileUtil.getDoor(this).getAbsolutePath(),hand_image_id_door);
        }else
        // 环境
        if (requestCode == REQUEST_CODE_ENVIRONMENT&& resultCode == Activity.RESULT_OK) {
            handenvironmentImageSuccess(FileUtil.getEnvironment(this).getAbsolutePath(),hand_image_id_enerment);
        }else{
            IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (scanResult != null) {
                String result = scanResult.getContents();
                snEt.setText(result);
            }

        }
    }

    //门头
    private void handdoorImageSuccess(String mImagePath,ImageView iv) {
        base64_door = "data:image/png;base64," + compress(mImagePath);
        GlideApp.with(this)
                .load(mImagePath)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(iv);
        iv.setScaleType(ImageView.ScaleType.FIT_XY);

    }
    //环境
    private void handenvironmentImageSuccess(String mImagePath,ImageView iv) {
        base64_environment = "data:image/png;base64," + compress(mImagePath);
        GlideApp.with(this)
                .load(mImagePath)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(iv);
        iv.setScaleType(ImageView.ScaleType.FIT_XY);

    }
    //身份证正面
    private void handleidccardImageSuccess(String mImagePath,ImageView iv) {
        base64_id_front = "data:image/png;base64," + compress(mImagePath);
        GlideApp.with(this)
                .load(mImagePath)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(iv);
        iv.setScaleType(ImageView.ScaleType.FIT_XY);

    }
    //身份证背面
    private void handleidccardbackImageSuccess(String mImagePath,ImageView iv) {
        base64_id_back = "data:image/png;base64," + compress(mImagePath);
        GlideApp.with(this)
                .load(mImagePath)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(iv);
        iv.setScaleType(ImageView.ScaleType.FIT_XY);

    }
    //银行卡正面
    private void handlebankccardImageSuccess(String mImagePath,ImageView iv) {
        base64_back_card = "data:image/png;base64," + compress(mImagePath);
        GlideApp.with(this)
                .load(mImagePath)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(iv);
        iv.setScaleType(ImageView.ScaleType.FIT_XY);

    }
    //银行卡背面
    private void handlebankcardbackImageSuccess(String mImagePath,ImageView iv) {
        base64_back_card_back = "data:image/png;base64," + compress(mImagePath);
        GlideApp.with(this)
                .load(mImagePath)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(iv);
        iv.setScaleType(ImageView.ScaleType.FIT_XY);

    }
    //人脸
    private void handImageSuccess(String mImagePath,ImageView iv) {
        base64_hand = "data:image/png;base64," + compress(mImagePath);
        GlideApp.with(this)
                .load(mImagePath)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(iv);
        iv.setScaleType(ImageView.ScaleType.FIT_XY);

    }
    //营业执照
    private void handlebussissImageSuccess(String mImagePath,ImageView iv) {
        base64_business_license = "data:image/png;base64," + compress(mImagePath);
        GlideApp.with(this)
                .load(mImagePath)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(iv);
        iv.setScaleType(ImageView.ScaleType.FIT_XY);

    }

    private void requestVerifyCode() {
        if (TextUtils.isEmpty(phoneEt.getText()) || TextUtils.isEmpty(phoneEt.getText().toString().trim())) {
            ToastUtil.showNormal(this, "请输入手机号码");
            return;
        }
        if (timer != null) {
            timer.cancel();
        }
        getVerifyCode.setEnabled(false);
        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long l) {
                getVerifyCode.setText(l / 1000 + "秒后重发");
            }

            @Override
            public void onFinish() {
                getVerifyCode.setEnabled(true);
                getVerifyCode.setText("获取验证码");
            }
        };
        timer.start();

        String phone = phoneEt.getText().toString().trim();
        PhoneNumerParamBean p = new PhoneNumerParamBean();
        p.setTelephoneNumber(phone);
        Call<PhoneNumerBean> userMsgCall2 = HelloWordModel.getInstance(this).getphonecode(SystemDatas.GetService_URL
                ("getphonecode2"), p);
        userMsgCall2.enqueue(new retrofit2.Callback<PhoneNumerBean>() {
            @Override
            public void onResponse(Call<PhoneNumerBean> call, final Response<PhoneNumerBean> response) {
               try{
                if (response.body() != null && response.body().getMsg().equals("success")) {
                    ToastUtil.showNormal(OldPosAuthByHandActivity.this, "获取成功!");
                    mCode = response.body().getData().getCode();
                } else {
                    ToastUtil.showNormal(OldPosAuthByHandActivity.this, response.body().getMsg());
                }
               } catch (Exception e) {
                   e.printStackTrace();
               }
            }

            @Override
            public void onFailure(Call<PhoneNumerBean> call, Throwable t) {
                ToastUtil.showNormal(OldPosAuthByHandActivity.this, "获取失败");
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (citySelectView.getVisibility() == View.VISIBLE) {
            citySelectView.setVisibility(View.GONE);
            return;
        }
        super.onBackPressed();
    }

    private boolean checkDetailInput() {
        if (TextUtils.isEmpty(mCode) || !TextUtils.equals(mCode, verifyCodeEt.getEditableText().toString())) {
            return false;
        }


        return !TextUtils.isEmpty(phoneEt.getEditableText().toString())
                && !TextUtils.isEmpty(bankCardNoEt.getEditableText().toString())
                && !TextUtils.isEmpty(bankCardNameEt.getEditableText().toString())
                && !TextUtils.isEmpty(snEt.getEditableText().toString())
                && !TextUtils.isEmpty(detailIdName.getText().toString())
                && !TextUtils.isEmpty(detailIdNo.getText().toString())
                && !TextUtils.isEmpty(mAddressCode)
                && !TextUtils.isEmpty(base64_id_front)
                && !TextUtils.isEmpty(base64_id_back)
                && !TextUtils.isEmpty(base64_hand)
                && !TextUtils.isEmpty(base64_back_card)
                && !TextUtils.isEmpty(base64_back_card_back)
                && !TextUtils.isEmpty(base64_business_license)
                && !TextUtils.isEmpty(base64_door)
                && !TextUtils.isEmpty(base64_environment)
                && !TextUtils.isEmpty(detailAddressEt.getEditableText().toString())
                && !TextUtils.isEmpty(openAccountBankEt.getEditableText().toString())
                && !TextUtils.isEmpty(mMerchantType);
    }
    // 自定义申请多个权限
    private void requestMorePermissions(int status) {
        PermissionUtils.checkMorePermissions(OldPosAuthByHandActivity.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
            @Override
            public void onHasPermission() {
                switch (status){
                    case 1:
                            OCRUtils.startBusinessLicense2(OldPosAuthByHandActivity.this, REQUEST_CODE_BUSINESS_LICENSE);
                        break;
                    case 2:
                        OCRUtils.startIDCardFront(OldPosAuthByHandActivity.this, REQUEST_CODE_PICK_IMAGE_FRONT);
                        break;
                    case 3:
                        OCRUtils.startIDCardBack(OldPosAuthByHandActivity.this, REQUEST_CODE_PICK_IMAGE_BACK);
                        break;
                    case 4:
                        OCRUtils.startFace2(OldPosAuthByHandActivity.this, REQUEST_CODE_FACE);
                        break;
                    case 5:
                        OCRUtils.startBankCard(OldPosAuthByHandActivity.this, REQUEST_CODE_BANKCARD);
                        break;
                    case 6:
                        OCRUtils.startBankCardBack2(OldPosAuthByHandActivity.this, REQUEST_CODE_BANKCARDBACK);
                        break;
                    case 7:
                        OCRUtils.startDoor(OldPosAuthByHandActivity.this, REQUEST_CODE_DOOR);
                        break;
                    case 8:
                        OCRUtils.startEnvironment(OldPosAuthByHandActivity.this, REQUEST_CODE_ENVIRONMENT);
                        break;
                }

            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {
                showExplainDialog(permission, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PermissionUtils.requestMorePermissions(OldPosAuthByHandActivity.this, PERMISSIONS, REQUEST_WRITE);
                    }
                });
            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                PermissionUtils.requestMorePermissions(OldPosAuthByHandActivity.this, PERMISSIONS, REQUEST_WRITE);
            }
        });
    }


    /**
     * 解释权限的dialog
     */
    private void showExplainDialog(String[] permission, DialogInterface.OnClickListener onClickListener) {
        new AlertDialog.Builder(OldPosAuthByHandActivity.this)
                .setTitle("申请权限")
                .setMessage("我们需要" + Arrays.toString(permission) + "权限")
                .setPositiveButton("确定", onClickListener)
                .show();
    }

    /**
     * 显示前往应用设置Dialog
     */
    private void showToAppSettingDialog() {
        new AlertDialog.Builder(OldPosAuthByHandActivity.this)
                .setTitle("需要权限")
                .setMessage("我们需要相关权限，才能实现功能，点击前往，将转到应用的设置界面，请开启应用的相关权限。")
                .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PermissionUtils.toAppSetting(OldPosAuthByHandActivity.this);
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {

            case REQUEST_WRITE:
                PermissionUtils.onRequestMorePermissionsResult(OldPosAuthByHandActivity.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
                    @Override
                    public void onHasPermission() {

                    }

                    @Override
                    public void onUserHasAlreadyTurnedDown(String... permission) {
                        Toast.makeText(OldPosAuthByHandActivity.this, "我们需要获取拍照等权限", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                        Toast.makeText(OldPosAuthByHandActivity.this, "我们需要获取拍照等权限", Toast.LENGTH_SHORT).show();
                        showToAppSettingDialog();
                    }
                });
        }
    }

}
